package rsa

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"io/ioutil"
	"log"
	"os"
)

func LoadPublicKey(workDir string, publicKey string) error {
	pubKey, err := ioutil.ReadFile(workDir + "/" + publicKey + "/" + publicKey + ".pub")
	if err != nil {
		return err
	}
	if err := RSA.SetPublicKey(string(pubKey)); err != nil {
		return err
	}
	return nil

}
func LoadPrivateKey(workDir string, privateKey string) error {
	key, err := ioutil.ReadFile(workDir + "/" + privateKey + "/" + privateKey + ".key")
	if err != nil {
		return err
	}
	if err := RSA.SetPrivateKey(string(key)); err != nil {
		return err
	}
	return nil
}

// GenerateRSAKey 生成RSA私钥和公钥，保存到文件中
func GenerateRSAKey(workDir string, bits int, id string) {
	dir := workDir + "/" + id
	log.Println("dir:", dir)
	err := os.MkdirAll(dir, 0755)
	if err != nil {
		log.Println("创建目录错误：", dir)
	}
	//GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
	//Reader是一个全局、共享的密码用强随机数生成器
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		panic(err)
	}
	//保存私钥
	//通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
	X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
	//使用pem格式对x509输出的内容进行编码
	//创建文件保存私钥
	privateFile, err := os.Create(dir + "/" + id + ".key")
	if err != nil {
		panic(err)
	}
	defer privateFile.Close()
	//构建一个pem.Block结构体对象
	privateBlock := pem.Block{Type: "RSA Private Key " + id, Bytes: X509PrivateKey}
	//将数据保存到文件
	pem.Encode(privateFile, &privateBlock)

	//保存公钥
	//获取公钥的数据
	publicKey := privateKey.PublicKey
	//X509对公钥编码
	X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		panic(err)
	}
	//pem格式编码
	//创建用于保存公钥的文件
	publicFile, err := os.Create(dir + "/" + id + ".pub")
	if err != nil {
		panic(err)
	}
	defer publicFile.Close()
	//创建一个pem.Block结构体对象
	publicBlock := pem.Block{Type: "RSA Public Key " + id, Bytes: X509PublicKey}
	//保存到文件
	pem.Encode(publicFile, &publicBlock)
}
